package com.carltechnology.mahjonggamecaculation.presenter.impl;

import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.carltechnology.mahjonggamecaculation.R;
import com.carltechnology.mahjonggamecaculation.base.MyAbstractSubscriber;
import com.carltechnology.mahjonggamecaculation.base.MyApplication;
import com.carltechnology.mahjonggamecaculation.dao.DataManager;
import com.carltechnology.mahjonggamecaculation.mode.IDetailGameData;
import com.carltechnology.mahjonggamecaculation.mode.IGameData;
import com.carltechnology.mahjonggamecaculation.mode.IGameRuntimeData;
import com.carltechnology.mahjonggamecaculation.mode.impl.GameDetailDataMode;
import com.carltechnology.mahjonggamecaculation.mode.impl.GameRuntimeDataMode;
import com.carltechnology.mahjonggamecaculation.presenter.IMahjongRunningGamePresenter;
import com.carltechnology.mahjonggamecaculation.utils.Utils;
import com.carltechnology.mahjonggamecaculation.views.IMahjongRunningGameView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by WZTCM on 2016/7/1.
 */
public class MahjongRunningGamePresenter extends RecyclerView.OnScrollListener implements IMahjongRunningGamePresenter {
    private MyRunningGameAdapter adapter;
    private IMahjongRunningGameView mView;
    private MyCaculationHelper caculationHelper;
    private final int perunit;

    private MahjongRunningGamePresenter(IMahjongRunningGameView mView) {

        this.mView = mView;
        this.perunit = MyApplication.getPool().getPerUnit();
        List<IGameRuntimeData> list = new ArrayList<>();
        caculationHelper = new MyCaculationHelper();
        adapter = new MyRunningGameAdapter(list);
        RecyclerView recyclerView = mView.getRecycleView();
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(adapter));
        recyclerView.addOnScrollListener(this);
        MyApplication.getPool().getGameMode().update();
        if (Utils.getInstance().getRuntimeDataHelper().isRuntime()){
            DataManager.getInstance().getDataSourceHelper().getMahjongRuntimeInfo(new MyRuntimeSubscriber());
        }

    }

    public static IMahjongRunningGamePresenter newInstance(IMahjongRunningGameView view) {
        return new MahjongRunningGamePresenter(view);
    }

    @Override
    public void insertMode(IGameRuntimeData mode) {
        adapter.add(mode);
        caculationHelper.doCaculation(mode);
    }

    @Override
    public void modifyMode(int pos, int[] counts, int cost) {
        adapter.modify(pos, counts, cost);
    }

    @Override
    public void onDestroy() {
        caculationHelper.onCompleted();
    }



    public GameDetailDataMode getDetailMode() {
        int [] prices = new int [4];
        prices[0]=caculationHelper.getAccount1();
        prices[1]=caculationHelper.getAccount2();
        prices[2]=caculationHelper.getAccount3();
        prices[3]=caculationHelper.getAccount4();
        return GameDetailDataMode
                ._of(MyApplication.getPool().getGameMode().getId()
                        ,prices,caculationHelper.getCost()
                        ,MyApplication.getPool().getPerUnit());
    }


    class MyRunningGameAdapter extends RecyclerView.Adapter<MyRunningGameAdapter.MyViewHolder>
            implements StickyRecyclerHeadersAdapter<MyRunningGameAdapter.MyHeaderHolder> {
        private List<IGameRuntimeData> modeList;

        public MyRunningGameAdapter(List<IGameRuntimeData> modeList) {
            this.modeList = modeList;
        }

        public void add(IGameRuntimeData mode) {
            modeList.add(mode);
            Utils.getInstance().getRuntimeDataHelper(null).insertRuntimeData(mode);
            notifyDataSetChanged();
        }

        public void clearUp() {
            modeList.clear();
            notifyDataSetChanged();
        }
        void storeAllMode(){

        }
        public void modify(int pos, int[] counts, int cost) {
            IGameRuntimeData mode = modeList.get(pos);
            GameRuntimeDataMode mode1 = GameRuntimeDataMode._of((GameRuntimeDataMode) mode);
            mode.doModifying(counts, cost);
            GameRuntimeDataMode mode2 = GameRuntimeDataMode._of((GameRuntimeDataMode) mode);
            notifyDataSetChanged();
            List<IGameRuntimeData> list = new ArrayList<>();
            list.add(mode1);
            list.add(mode2);
            caculationHelper.modifyHelper.onNext(list);
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.mahjonggame_percontent_list_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            final IGameRuntimeData mode = modeList.get(position);
            int[] accounts = mode.getGameCount();
            holder.label.setText(String.valueOf(position + 1));
            holder.account1.setText(String.valueOf(accounts[0]));
            holder.account2.setText(String.valueOf(accounts[1]));
            holder.account3.setText(String.valueOf(accounts[2]));
            holder.account4.setText(String.valueOf(accounts[3]));
            holder.cost.setText(String.valueOf(mode.getCost()));
            holder.modifyLabel.setBackgroundColor(getModifyColor(mode.getModifyCount()));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!mode.canBeModified()) {
                        Snackbar.make(mView.getRecycleView(),
                                "无法再改变",
                                Snackbar.LENGTH_SHORT)
                                .setAction("Undo", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                })
                                .show();
                        return;
                    }
                    GameRuntimeDataMode reqMode
                            = GameRuntimeDataMode._of((GameRuntimeDataMode) mode);
                    mView.ToModifyActivity(position, reqMode);
                }
            });
        }

        @Override
        public long getHeaderId(int position) {
            return 0;
        }

        @Override
        public MyHeaderHolder onCreateHeaderViewHolder(ViewGroup parent) {
            return new MyHeaderHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_runninggame_header_bar, parent, false));
        }

        @Override
        public void onBindHeaderViewHolder(MyHeaderHolder holder, int position) {

            IGameData mode = MyApplication.getPool().getGameMode();
            String[] names = mode.getValues();
            //            String [] names;
            //            names=new String[]{"sdf","sdf","sdf","sdf"};
            holder.label.setText("标签");
            holder.account1.setText(names[0]);
            holder.account2.setText(names[1]);
            holder.account3.setText(names[2]);
            holder.account4.setText(names[3]);
            holder.cost.setText("台费");
            holder.modifyLabel.setText("修改次数");
            holder.itemView.setBackgroundColor(getColor(50));
        }

        @Override
        public int getItemCount() {
            return modeList == null ? 0 : modeList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            @InjectView(R.id.mahjonggame_percontent_label)
            TextView label;
            @InjectView(R.id.mahjonggame_percontent_account1)
            TextView account1;
            @InjectView(R.id.mahjonggame_percontent_account2)
            TextView account2;
            @InjectView(R.id.mahjonggame_percontent_account3)
            TextView account3;
            @InjectView(R.id.mahjonggame_percontent_account4)
            TextView account4;
            @InjectView(R.id.mahjonggame_percontent_modifylabel)
            TextView modifyLabel;
            @InjectView(R.id.mahjonggame_percontent_cost)
            TextView cost;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.inject(this, itemView);
            }
        }

        private int getColor(int color) {
            SecureRandom rgen = new SecureRandom();
            if (color < 0 || color > 359) {
                color = rgen.nextInt(359);
            }
            return Color.HSVToColor(150, new float[]{
                    color, 1, 1
            });
        }

        class MyHeaderHolder extends RecyclerView.ViewHolder {
            @InjectView(R.id.mahjonggame_runningheader_account1)
            TextView account1;
            @InjectView(R.id.mahjonggame_runningheader_account2)
            TextView account2;
            @InjectView(R.id.mahjonggame_runningheader_account3)
            TextView account3;
            @InjectView(R.id.mahjonggame_runningheader_account4)
            TextView account4;
            @InjectView(R.id.mahjonggame_runningheader_cost)
            TextView cost;
            @InjectView(R.id.mahjonggame_runningheader_label)
            TextView label;
            @InjectView(R.id.mahjonggame_runningheader_modifylabel)
            TextView modifyLabel;

            public MyHeaderHolder(View itemView) {
                super(itemView);
                ButterKnife.inject(this, itemView);
            }
        }
    }

    private int getModifyColor(int changeNumber) {
        int res = -1;
        switch (changeNumber) {
            case 0:
                res = Color.WHITE;
                break;
            case 1:
                res = Color.RED;
                break;
            case 2:
                res = Color.YELLOW;
                break;
            case 3:
                res = Color.GREEN;
                break;
            case 4:
                res = Color.CYAN;
                break;
            case 5:
                res = Color.BLUE;
                break;
            case 6:
                res = Color.GRAY;
                break;
            default:
                res = Color.BLACK;
        }
        return res;
    }

    class MyCaculationHelper {
        Subscriber<? super IGameRuntimeData> subsHelper;
        Subscriber<? super List<IGameRuntimeData>> modifyHelper;
        private int account1 = 0;
        private int account2 = 0;
        private int account3 = 0;
        private int account4 = 0;
        private int cost = 0;

        public MyCaculationHelper() {
            Observable.create(new Observable.OnSubscribe<IGameRuntimeData>() {
                @Override
                public void call(Subscriber<? super IGameRuntimeData> subscriber) {
                    subsHelper = subscriber;
                }
            })
                    .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SIZE.getConstant())
                    .observeOn(Schedulers.computation())
                    .subscribe(new Action1<IGameRuntimeData>() {
                        @Override
                        public void call(IGameRuntimeData iGameRuntimeData) {
                            final int[] add = iGameRuntimeData.getGameCount();
                            final int[] resAdd = new int[5];
                            // final int resCost;
                            synchronized (adapter) {
                                account1 += add[0] * perunit;
                                resAdd[0] = account1;
                                account2 += add[1] * perunit;
                                resAdd[1] = account2;
                                account3 += add[2] * perunit;
                                resAdd[2] = account3;
                                account4 += add[3] * perunit;
                                resAdd[3] = account4;
                                cost += iGameRuntimeData.getCost() * perunit;
                                resAdd[4] = cost;
                            }
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mView.getAccount1().setText(String.valueOf(resAdd[0]));
                                    mView.getAccount2().setText(String.valueOf(resAdd[1]));
                                    mView.getAccount3().setText(String.valueOf(resAdd[2]));
                                    mView.getAccount4().setText(String.valueOf(resAdd[3]));
                                    mView.getCost().setText(String.valueOf(resAdd[4]));
                                }
                            });

                        }
                    });
            Observable.create(new Observable.OnSubscribe<List<IGameRuntimeData>>() {
                @Override
                public void call(Subscriber<? super List<IGameRuntimeData>> subscriber) {
                    modifyHelper = subscriber;
                }
            })
                    .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SMALL_SIZE.getConstant())
                    .subscribeOn(Schedulers.computation())
                    .observeOn(Schedulers.computation())
                    .filter(new Func1<List<IGameRuntimeData>, Boolean>() {
                        @Override
                        public Boolean call(List<IGameRuntimeData> iGameRuntimeDatas) {
                            if (iGameRuntimeDatas.size() != 2)
                                return false;
                            return true;
                        }
                    })
                    .subscribe(new Action1<List<IGameRuntimeData>>() {
                        @Override
                        public void call(List<IGameRuntimeData> iGameRuntimeDatas) {
                            IGameRuntimeData mode1 = iGameRuntimeDatas.get(0);
                            IGameRuntimeData mode2 = iGameRuntimeDatas.get(1);
                            final int[] res = new int[5];
                            synchronized (adapter) {
                                account1 += (mode2.getGameCount()[0] - mode1.getGameCount()[0]) * perunit;
                                account2 += (mode2.getGameCount()[1] - mode1.getGameCount()[1]) * perunit;
                                account3 += (mode2.getGameCount()[2] - mode1.getGameCount()[2]) * perunit;
                                account4 += (mode2.getGameCount()[3] - mode1.getGameCount()[3]) * perunit;
                                cost += (mode2.getCost() - mode1.getCost()) * perunit;
                                res[0] = account1;
                                res[1] = account2;
                                res[2] = account3;
                                res[3] = account4;
                                res[4] = cost;
                            }
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mView.getAccount1().setText(String.valueOf(res[0]));
                                    mView.getAccount2().setText(String.valueOf(res[1]));
                                    mView.getAccount3().setText(String.valueOf(res[2]));
                                    mView.getAccount4().setText(String.valueOf(res[3]));
                                    mView.getCost().setText(String.valueOf(res[4]));
                                }
                            });
                        }
                    });
        }

        public void doCaculation(IGameRuntimeData mode) {
            subsHelper.onNext(mode);
        }

        public int getAccount1() {
            return account1;
        }

        public int getAccount2() {
            return account2;
        }

        public int getAccount3() {
            return account3;
        }

        public int getAccount4() {
            return account4;
        }

        public int getCost() {
            return cost;
        }

        public void onCompleted() {
            subsHelper.unsubscribe();
            modifyHelper.unsubscribe();
        }

    }
    @Override
    public void finishRunningGame() {
        GameDetailDataMode mode = getDetailMode();
        DataManager.getInstance().getInsertHelper().insertMahjongDetailGameData(new MyDataInsertSubscriber(),mode);
        //DataManager.getInstance().getModifyHelper().clearRuntimeGameData();
    }



    class MyDataInsertSubscriber extends MyAbstractSubscriber<IDetailGameData>{

        @Override
        public void onNext(IDetailGameData gameDetailDataMode) {

        }
    }
    class MyRuntimeSubscriber extends MyAbstractSubscriber<IGameRuntimeData>{

        @Override
        public void onNext(IGameRuntimeData iGameRuntimeData) {
            insertMode(iGameRuntimeData);
        }
    }

}
